package mysql_models

import (
	"database/sql"
	"go-scripts/common"
	"errors"
)

type User struct {
	Id int `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
}

type UserDao struct {
	db *sql.DB
	logger *common.Log
}

var userDao *UserDao

func GetUserDao() *UserDao {
	if userDao != nil {
		return userDao
	}
	userDao := new(UserDao)
	//userDao.db = GetMysqlModel("jingx")
	userDao.logger = common.GetLogger()
	return userDao
}

func (dao *UserDao) Save(userInfos map[string]interface{}) (int64, error) {
	saveSql, values := formatSaveSql("user", userInfos)
	if saveSql == "" {
		return -1, errors.New("map do not have any value")
	}
	dao.logger.Info(saveSql)
	result, err := dao.db.Exec(saveSql, values...)
	if err != nil {
		return -1, err
	}
	return result.LastInsertId()
}

func (dao *UserDao) FindByUsername(username string) ([]* User, error) {
	rows, err := dao.db.Query("select * from user where username = ?", username)
	users := []*User{}
	for rows.Next() {
		user := new(User)
		err = rows.Scan(&user.Id, &user.Username, &user.Password)
		if err != nil {
			return users, err
		}
		users = append(users, user)
	}
	return users, nil
}